<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Upload extends CI_Controller {
	
	function __construct() {
		parent::__construct();
	}
	
	function index(){
		$this->load->library("session_manager");
		$sm = $this->session_manager;
		
		$data = array(
			"title" => "Upload - Upload Files",
			"jsarray" => array(
				"resources/js/jquery.form.js",
				"resources/js/upload.js"
			),
			"extra" => '<link rel="stylesheet" href="'.base_url().'resources/css/upload.css" type="text/css" media="screen, projection" />'
		);
		
		$this->load->view("header", $data);

		$data = array("nickname" => $sm->user['nickname']);
		$this->load->view("menu", $data);
		
		$data = array("sid" => session_id());
		$this->load->view("upload", $data);
		
		$this->load->view("footer");
	
	}
	
	function upload_file() {
		$this->load->library("session_manager");
		$sm = $this->session_manager;
		
		set_time_limit(UPLOAD_EXEC_TIME);
			
		if (!empty($_FILES)) {
			$tempFile = $_FILES['upload_file']['tmp_name'];
			
			$upload_time=time();
			
			//目标文件
			$targetPath = $this->_build_path($sm->user['uid'],$upload_time);
			$targetFilename = $this->_build_filename($_FILES['upload_file']['name']);
			$targetFile =  str_replace('//','/',$targetPath) ."/". $targetFilename;
			
			//判断文件类型
			$fileParts  = pathinfo($_FILES['upload_file']['name']);
			if (in_array(strtolower($fileParts['extension']),get_filetypes())) {
			
				$res = @move_uploaded_file($tempFile,$targetFile);

				if ($res && file_exists($targetFile)){
					
					//判断文件格式是否正常，获取文件生成时间
					$handle = fopen($targetFile, "r");
					$contents = fread($handle, 19);
					fclose($handle);
					if (preg_match('/20(\d{2})-([0|1][0-9])-([0-3][0-9]),([0-2][0-9]):([0-5][0-9]):([0-5][0-9])/',$contents))
					{
						$gen_time = @strtotime(str_replace(',',' ',$contents));
						
						$description = (isset($_POST['description']) && $_POST['description']) ? addslashes(trim($_POST['description'])) : @date('Y-m-d H:i:s',$gen_time+TIME_OFFSET)."轨迹记录";
					
						//数据库操作
						$this->load->database();
						$this->load->model("Gps_log_source");
						
						//数据库存储
						$sid = $this->Gps_log_source->insert_log($sm->user['uid'],$targetFilename, $upload_time, $gen_time, $description);
	
						echo "转存成功。文件上传完成。<script Language='Javascript'>\$('.progress').hide(); \$('#submit_file').hide(); window.location='".site_url()."/parse/index/".$sid."';</script>";				
					}
					else
					{
						@unlink($targetFile);	
						echo "文件格式错误，请确认数据文件的正确性。";				
					}
					
				} else
					echo "转存文件失败！";
			} else {
			 	echo '非法的文件类型。';
			}
		}
		
	}

	function _build_path($uid,$timestamp){
		$dirs = array(
			$uid,
			'src',
			@date("Y", $timestamp),
			@date("m", $timestamp),
			@date("d", $timestamp)
		);
		
		$path = base_dir().STORAGE_PATH;
		foreach ($dirs as $dir){
			$path .="/".$dir;
			if (!is_dir($path)) {
				mkdir($path);
			}
		}
				
		return $path;
	}
	
	function _build_filename($filename){
		$fileParts  = pathinfo($filename);
		
		$title = md5(basename($fileParts['basename'],$fileParts['extension']));

		return time()."_".$title.".".strtolower($fileParts['extension']);
		
	}
}
?>